package com.nova.bluetooth.xunFeiSDK.optionalFunction;


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.aiui.AIUIAgent;
import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIListener;
import com.nova.bluetooth.R;
import com.nova.bluetooth.xunFeiSDK.engine.AiuiEngine;
import com.nova.bluetooth.xunFeiSDK.engine.EngineConstants;
import com.nova.bluetooth.xunFeiSDK.utils.CopyAssetsUtils;
import com.nova.bluetooth.xunFeiSDK.utils.FileUtil;
import com.nova.bluetooth.xunFeiSDK.utils.senselessWordUtil;


import java.nio.charset.StandardCharsets;

/**
 * 发送文本请求语义
 */
public class TextNlpActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
    private static final String TAG = TextNlpActivity.class.getSimpleName();
    Handler handler = new Handler();
    private TextView mResText;
    private TextView mTile;
    private ScrollView mScrollView;
    private ScrollView mScrollViewEdit;
    private EditText mEditText;
    private Button mButtonSave;
    // AIUI
    private AIUIAgent mAIUIAgent = null;

    /**
     * AIUI 回调信息处理
     */
    private AIUIListener mAIUIListener = event -> {
        switch (event.eventType) {
            //其他事件请参照AsrActivity开发，这个demo仅展示流式识别
            case AIUIConstant.EVENT_RESULT:
                //处理语义结果
                if (event.info.contains("\"sub\":\"nlp")) {
                    JSONObject cntJson = JSON.parseObject(new String(event.data.getByteArray("0"), StandardCharsets.UTF_8));
                    JSONObject nlpResult = cntJson.getJSONObject("intent");
                    //nlp无结果不处理
                    if (nlpResult.isEmpty()) {
                        return;
                    }
                    //如果只判断asr结果中的无意义词，若nlp先返回就可能被错误判断为无意义词
                    String asrResult = nlpResult.getString("text");
                    EngineConstants.meaningful = senselessWordUtil.isMeaningful_filter1word(asrResult);
                    //无意义词不处理
                    if (!EngineConstants.meaningful) {
                        return;
                    }
                    Log.i(TAG, "nlp result :" + nlpResult);
                    //在线语义结果,rc=0语义理解成功，rc≠0语义理解失败
                    mEditText.setText(nlpResult.toString());
                }
                break;
            case AIUIConstant.EVENT_STATE:    // 状态事件
                EngineConstants.mAIUIState = event.arg1;
                break;
            default:
                break;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asr);
        initLayout();
        FileUtil.requestPermissions(this);
        // 资源拷贝
        CopyAssetsUtils.portingFile(this);
    }

    private void initLayout() {
        findViewById(R.id.init_sdk).setOnClickListener(this);
        findViewById(R.id.btnStartRecord).setOnClickListener(this);
        mButtonSave = findViewById(R.id.btnSave);
        mButtonSave.setText("清空文本");
        mButtonSave.setOnClickListener(this);
        findViewById(R.id.btnStopRecord).setVisibility(View.GONE);
        mTile = findViewById(R.id.myTitle);
        mTile.setText("文本语义Demo");
        mTile.setOnLongClickListener(this);
        ((Button) findViewById(R.id.btnStartRecord)).setText("发送文本");
        mScrollView = findViewById(R.id.scrollView);
        mScrollView.setVisibility(View.GONE);
        mScrollViewEdit = findViewById(R.id.scrollViewEdit);
        mScrollViewEdit.setVisibility(View.VISIBLE);
        mResText = findViewById(R.id.res_text);
        mEditText = findViewById(R.id.res_edittext);
        mEditText.setHint("文本语义demo，输入文本获取语义结果\n默认为请求“明天的天气怎么样”");
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.init_sdk) {
            initSDK();
        } else if (id == R.id.btnStartRecord) {
            startRecord();
        } else if (id == R.id.btnSave) {
            mEditText.setText("");
        }
    }

    @Override
    public boolean onLongClick(View view) {
        if (view.getId() == R.id.myTitle) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText(null, mEditText.getText());
            clipboard.setPrimaryClip(clipData);
            Toast.makeText(this, "已复制到剪贴板", Toast.LENGTH_LONG).show();
        }
        return true;
    }


    private void initSDK() {
        //状态初始化
        EngineConstants.isRecording = false;
        EngineConstants.isWriting = false;
        //TODO 开发者需要实现生成sn的代码，参考：https://www.yuque.com/iflyaiui/zzoolv/tgftb5
        //注意事项1: sn每台设备需要唯一！！！！WakeupEngine的sn和AIUI的sn要一致
        //注意事项2: 获取的值要保持稳定，否则会重复授权，浪费授权量
        EngineConstants.serialNumber = "iflytek-test";
        Log.i(TAG, "sn : " + EngineConstants.serialNumber);
        // 初始化AIUI(识别+语义+合成）
        mAIUIAgent = AiuiEngine.getInstance(mAIUIListener);
        if (mAIUIAgent != null) {
            setText("AIUI初始化成功");
        } else {
            setText("AIUI初始化失败");
        }
    }


    private void startRecord() {
        //发送文本语义
        String text = mEditText.getText().toString();
        text = text.isEmpty() ? "明天的天气怎么样" : text;
        AiuiEngine.MSG_sendTextForNlp(text);
    }

    /**
     * 根据scrollView 和子view去测量滑动的位置
     *
     * @param scrollView
     * @param view
     */
    private void scrollToBottom(final ScrollView scrollView, final View view) {

        handler.post(() -> {
            if (scrollView == null || view == null) {
                return;
            }
            // offset偏移量。是指当textview中内容超出 scrollview的高度，那么超出部分就是偏移量
            int offset = view.getMeasuredHeight()
                    - scrollView.getMeasuredHeight();
            if (offset < 0) {
                offset = 0;
            }
            //scrollview开始滚动
            scrollView.scrollTo(0, offset);
        });
    }

    private void setText(final String str) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            mResText.append(str + " \n");
            scrollToBottom(mScrollView, mResText);
        } else {
            runOnUiThread(() -> {
                mResText.append(str + " \n");
                scrollToBottom(mScrollView, mResText);
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAIUIListener != null) {
            mAIUIListener = null;
        }
        AiuiEngine.destroy();
    }


}